<template>
  <div class="callback-container" />
  <!-- <div>
    {{ data }}
  </div> -->
</template>

<script>
  import router from '@/router'
  import qs from 'qs'
  import { useUserStore } from '@/store/modules/user'

  export default defineComponent({
    name: 'Callback',
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseLoading = inject('$baseLoading')
      const loading = $baseLoading(0, '正在登录中...')

      const userStore = useUserStore()

      let data = router.currentRoute.value.query
      if (JSON.stringify(data) === '{}')
        data = qs.parse(document.location.search.slice(1))

      console.log('window.location.href:', window.location.href)
      console.log('router.currentRoute.value:', router.currentRoute.value)
      console.log('calllback query data:', JSON.stringify(data))

      const goRedirect = (path) => {
        if (path && path != '/callback') {
          router.push({ path, replace: true }).then(() => {})
        } else {
          router.push({ path: '/index', replace: true }).then(() => {})
        }
      }

      const socialLogin = async () => {
        if (data.code) {
          //企业微信里的授权方式
          userStore
            .socialLogin({ code: data.code })
            .then((resp) => {
              console.log(resp)
              goRedirect(data.redirect)
            })
            .catch(() => {})
        } else if (data.auth_code) {
          //pc扫码授权你登录方式
          userStore
            .socialQrLogin({ authCode: data.auth_code })
            .then((resp) => {
              console.log(resp)
              goRedirect(data.redirect)
            })
            .catch(() => {})
        } else {
          $baseConfirm(`oauth授权跳转页面错误`, null, async () => {})
        }
        loading.close()
      }

      onUnmounted(() => {
        loading.close()
      })

      socialLogin()
      // onMounted(() => {
      //   socialLogin()
      // })

      return {
        data,
      }
    },
  })
</script>
